package com.example.myapplication.blue;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
//
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.myapplication.R;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


import com.example.myapplication.blue.connect.AcceptThread;
import com.example.myapplication.blue.connect.ConnectThread;
import com.example.myapplication.blue.connect.Constant;

public class BlueToothActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 0;
    private List<BluetoothDevice> mDeviceList = new ArrayList<>();
    private List<BluetoothDevice> mBondedDeviceList = new ArrayList<>();

    private BlueToothController mController = new BlueToothController();
    private Handler mUIHandler = new MyHandler();
    
    private ListView mListView;
    private DeviceAdapter mAdapter;
    private Toast mToast;

    private AcceptThread mAcceptThread;
    private ConnectThread mConnectThread;

//    ///广播1
//    private BroadcastReceiver receiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,-1);
//            switch (state) {
//                case BluetoothAdapter.STATE_OFF:
//                      Toast.makeText(context,"STATE_OFF",Toast.LENGTH_SHORT).show();
////                    showToast("STATE_OFF");
//                    break;
//                case BluetoothAdapter.STATE_ON:
//                    Toast.makeText(context,"STATE_ON",Toast.LENGTH_SHORT).show();
////                    showToast("STATE_ON");
//                    break;
//                case BluetoothAdapter.STATE_TURNING_ON:
//                    Toast.makeText(context,"STATE_TURNING_ON",Toast.LENGTH_SHORT).show();
////                    showToast("STATE_TURNING_ON");
//                    break;
//                case BluetoothAdapter.STATE_TURNING_OFF:
//                    Toast.makeText(context,"STATE_TURNING_OFF",Toast.LENGTH_SHORT).show();
////                    showToast("STATE_TURNING_OFF");
//                    break;
//                default:
////                    showToast("unknown STATE");
//                    Toast.makeText(context,"unknown STATE",Toast.LENGTH_SHORT).show();
//                    break;
//            }
//        }
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //initActionBar();
        setContentView(R.layout.activity_blue_tooth);
        initUI();

        ///第一个广播
        //IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        //registerReceiver(receiver,filter);

        ///第二个广播
//        IntentFilter filter2 = new IntentFilter();
//        //开始查找
//        filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
//        //结束查找
//        filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//        //查找设备
//        filter2.addAction(BluetoothDevice.ACTION_FOUND);
//        //设备扫描模式改变
//        filter2.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
//        //绑定状态
//        filter2.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//        registerReceiver(mReceiver,filter2);
        mController.turnOnBlueTooth(this,REQUEST_CODE);
    }

    ///广播2
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //开始查找
            if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                setProgressBarIndeterminateVisibility(true);
                //初始化数据列表
                mDeviceList.clear();
                mAdapter.notifyDataSetChanged();
                //结束查找
            }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                setProgressBarIndeterminateVisibility(false);
                //查找设备
            }else if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //找到一个，添加一个
                mDeviceList.add(device);
                mAdapter.notifyDataSetChanged();
                //设备扫描模式改变
            }else if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)){
                int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,0);
                if(scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
                    setProgressBarIndeterminateVisibility(true);
                }else{
                    setProgressBarIndeterminateVisibility(false);
                }
                //绑定状态
            }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
                BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(remoteDevice == null){
                    Toast.makeText(context,"no device",Toast.LENGTH_SHORT).show();
                }
                int status = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,0);
                if(status == BluetoothDevice.BOND_BONDED){
                    Toast.makeText(context,"已绑定",Toast.LENGTH_SHORT).show();
                }else if(status == BluetoothDevice.BOND_BONDING){
                    Toast.makeText(context,"绑定中...",Toast.LENGTH_SHORT).show();
                }else if(status == BluetoothDevice.BOND_NONE){
                    Toast.makeText(context,"未绑定",Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    //初始化UI界面
    private void initUI(){
        //初始化列表
        mListView = findViewById(R.id.device_list);
        //初始化适配器
        mAdapter = new DeviceAdapter(mDeviceList,this);
        //列表配置适配器
        mListView.setAdapter(mAdapter);
        //列表点击绑定事件
        mListView.setOnItemClickListener(bondDeviceClick);
    }

    ///重写-在创建选项菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //获取菜单Inflater提供者
        //菜单视图
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }

    ///重写-在选择项选择
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //获取当前列表项的id
        int id = item.getItemId();

        //如果id对应打开可见按钮
        if (id == R.id.enable_visibility) {
            mController.enableVisibly(this);
        }
        //如果id对应查找设备
        else if (id == R.id.find_device) {
            mAdapter.refresh(mDeviceList);
            mController.findDevice();
            mListView.setOnItemClickListener(bondDeviceClick);
        }
        //如果id对应查看已绑定设备
        else if (id == R.id.bonded_device) {
            mBondedDeviceList = mController.getBondedDeviceList();
            mAdapter.refresh(mBondedDeviceList);
            mListView.setOnItemClickListener(bondedDeviceClick);
        }
        //如果id对应监听
        else if( id == R.id.listening) {
            if( mAcceptThread != null) {
                mAcceptThread.cancel();
            }
            mAcceptThread = new AcceptThread(mController.getAdapter(), mUIHandler);
            mAcceptThread.start();
        }
        //如果id对应停止监听
        else if( id == R.id.stop_listening) {
            if( mAcceptThread != null) {
                mAcceptThread.cancel();
            }
        }
        //如果id对应断开连接
        else if( id == R.id.disconnect) {
            if( mConnectThread != null) {
                mConnectThread.cancel();
            }
        }
        //如果id对应发送Hello消息
        else if( id == R.id.say_hello) {
            say("Hello");
        }
        //如果id对应发送Hi消息
        else if( id == R.id.say_hi) {
            say("Hi");
        }

        return super.onOptionsItemSelected(item);
    }

    //发送文字
    private void say(String word) {
        //如果接受线程不为空
        if (mAcceptThread != null) {
            try {
                //接受线程发送数据 字符utf-8转码后发送
                mAcceptThread.sendData(word.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                //如果出错者打印异常
                e.printStackTrace();
            }
        }
        //如果连接线程不为空
        else if( mConnectThread != null) {
            try {
                //连接线程发送数据 字符utf-8转码后发送
                mConnectThread.sendData(word.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                //如果出错者打印异常
                e.printStackTrace();
            }
        }

    }
    

//    ///是否支持蓝牙
//    public void isSupportBlueTooth(View view){
//        boolean ret = mController.isSupportBlueTooth();
////        showToast("BlueTooth Support?"+ret);
//        Toast.makeText(this,"BlueTooth Support?"+ret,Toast.LENGTH_SHORT).show();
//    }
//
//    ///蓝牙状态
//    public void isBlueToothEnable(View view){
//        boolean ret = mController.getBlueToothStatus();
////        showToast("BlueTooth enable?"+ret);
//        Toast.makeText(this,"BlueTooth Support?"+ret,Toast.LENGTH_SHORT).show();
//    }
//    ///打开蓝牙
//    public void turnOnBlueTooth(View view){
//        mController.turnOnBlueTooth(this, REQUEST_CODE);
//    }
//
//    ///关闭蓝牙
//    public void turnOffBlueTooth(View view){
//        mController.turnOffBlueTooth(this, REQUEST_CODE);
//    }

    ///活动结果
//    protected void onActivityResult(int requestCode, int resultCode, Intent data){
//        super.onActivityResult(requestCode,resultCode,data);
//        if(requestCode == RESULT_OK){
//            Toast.makeText(this,"打开成功",Toast.LENGTH_SHORT).show();
//        }else{
//            Toast.makeText(this,"打开失败",Toast.LENGTH_SHORT).show();
//        }
//    }

//    ///打开可见
//    public void visibleToOpen(View view) {
//        System.out.println("打开可见");
//        mController.enableVisibly(this);
//    }
//
//    ///查找设备
//    public void findEquipment(View view) {
//        System.out.println("查找设备");
//        System.out.println("refresh--0");
////        mAdapter.refresh(mDeviceList);
//        mController.findDevice();
//        System.out.println("refresh--1");
////        mListView.setOnItemClickListener(bindDeviceClick);
//        System.out.println("refresh--2");
//    }
//
//    ///已绑定设备
//    public void bindingEquipment(View view) {
//        System.out.println("已绑定设备");
//        mBondedDeviceList = mController.getBondedDeviceList();
//        mAdapter.refresh(mBondedDeviceList);
//        mListView.setOnItemClickListener(null);
//    }

    ///绑定设备的点击
    @SuppressLint("MissingPermission")
    private AdapterView.OnItemClickListener bondDeviceClick = new AdapterView.OnItemClickListener(){

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
            //获取列表中的当前设备如果
            BluetoothDevice device = mDeviceList.get(i);
            //获取当前项目SDK版本 大于等于 奇巧巧克力
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                //则设备执行绑定
                device.createBond();
            }
        }
    };

    ///已经绑定设备的点击
    private AdapterView.OnItemClickListener bondedDeviceClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            ////获取列表中的当前设备如果
            BluetoothDevice device = mBondedDeviceList.get(i);
            //如果连接线程不等于空，则代表至少绑定了1台设备。
            //限制只能绑定1台设备
            if (mConnectThread != null) {
                //第二个连接线程销毁
                mConnectThread.cancel();
            }
            //连接线程  = 构建（设备，控制器的适配器，UI处理线程）
            mConnectThread = new ConnectThread(device, mController.getAdapter(), mUIHandler);
            ////连接线程开始执行
            mConnectThread.start();
        }
    };

    //UI处理线程
    private class MyHandler extends Handler {
        //处理消息
        public void handleMessage(Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case Constant.MSG_GOT_DATA:
                    showToast("data:" + String.valueOf(message.obj));
                    break;
                case Constant.MSG_ERROR:
                    showToast("error:" + String.valueOf(message.obj));
                    break;
                case Constant.MSG_CONNECTED_TO_SERVER:
                    showToast("连接到服务端");
                    break;
                case Constant.MSG_GOT_A_CLINET:
                    showToast("找到服务端");
                    break;
            }
        }
    }

    //设置toast的标准格式
    private void showToast(String text){
        if(mToast == null){
            mToast = Toast.makeText(this, text,Toast.LENGTH_SHORT);
            mToast.show();
        }
        else {
            mToast.setText(text);
            mToast.show();
        }

    }


    //退出时注销广播、注销连接过程、注销等待连接的监听

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //如果接收线程不为空，则销毁
        if (mAcceptThread != null) {
            mAcceptThread.cancel();
        }
        //如果接收线程不为空，则销毁
        if (mConnectThread != null) {
            mConnectThread.cancel();
        }

        //销毁注册广播
        unregisterReceiver(mReceiver);
    }

//    private void initActionBar(){
//        System.out.println("initActionBar--0");
////        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//        System.out.println("initActionBar--1");
//        setProgressBarIndeterminate(false);
//        System.out.println("initActionBar--2");
//        try{
//            System.out.println("initActionBar--3");
//            ViewConfiguration config = ViewConfiguration.get(this);
//            System.out.println("initActionBar--4");
//            Field menuKeyFiled = ViewConfiguration.class
//                    .getDeclaredField("sHasPermanentKeyFiled");
//            System.out.println("initActionBar--5");
//            if(menuKeyFiled != null ){
//                System.out.println("initActionBar--6");
//                menuKeyFiled.setAccessible(true);
//                menuKeyFiled.setBoolean(config,false);
//                System.out.println("initActionBar--7");
//            }
//        } catch (NoSuchFieldException e) {
//            System.out.println("initActionBar--8");
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            System.out.println("initActionBar--9");
//            e.printStackTrace();
//        }
//    }

}